package com.ymttest.database.mongo;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.ymatou.iapi.synctrade.parameter.mongo.HunterIndex;
import com.ymatou.iapi.synctrade.parameter.mongo.UserIndex;
import com.ymt.core.tool.Logger;
import com.ymttest.database.mongo.config.HunterIndexField;
import com.ymttest.database.mongo.config.MongoHunterConfig;
import com.ymttest.database.mongo.config.SchemaField;

public class HunterIndexQueryWapper {
	
	private MongoTemplate mongoHunterTemplate;

	public HunterIndexQueryWapper() {
		try {
			mongoHunterTemplate = new MongoHunterConfig().mongoHunterTemplate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getCollectionName(long hunterId) {
		long n = hunterId % 100;
		return SchemaField.HUNTER + n;
	}

	public <T> List<T> find(Query query, Integer hunterId, Class<T> outputType) {
		return mongoHunterTemplate.find(query, outputType,
				getCollectionName(hunterId));
	}

	public <T> List<T> aggregate(long hunterId, Aggregation aggregation,
			Class<T> outputType) {

		return mongoHunterTemplate.aggregate(aggregation,
				getCollectionName(hunterId), outputType).getMappedResults();
	}

	public HunterIndex findById(long orderId, long hunterId) {

		return mongoHunterTemplate.findById(orderId, HunterIndex.class,
				getCollectionName(hunterId));
	}

	public boolean exists(Query query, long hunterId) {
		return mongoHunterTemplate.exists(query, getCollectionName(hunterId));
	}

	public long count(Query query, long hunterId) {
		return mongoHunterTemplate.count(query, getCollectionName(hunterId));
	}

	public List<Long> queryOrderId(Query query, long hunterId) {
		query.fields().include(HunterIndexField.ID);
		List<UserIndex> userIndexs = mongoHunterTemplate.find(query,
				UserIndex.class, getCollectionName(hunterId));
		return userIndexs.stream().map(e -> e.getId())
				.collect(Collectors.toList());
	}

	public HunterIndex findByIdWithQuery(Query query, long orderId, long hunterId) {
		query.fields().include(HunterIndexField.ID);
		query.addCriteria(Criteria.where(HunterIndexField.ID).is(orderId));
		return mongoHunterTemplate.findOne(query, HunterIndex.class,
				getCollectionName(hunterId));
	}

	public static void main(String... args) {

		Criteria criteria = Criteria.where(HunterIndexField.ID).gte(1132728699);

		Query.query(criteria);

		/*		Logger.info("userindex:"
						+ new UserIndexQueryWapper().findByIdWithQuery(q, 1132728699,
								20238699).getAddTime());*/

		Logger.info("Hunterindex:"
				+ new HunterIndexQueryWapper().findById(1869988699, 1234)
						.getAddTime());

	}
}
